/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Peer;

/**
 *
 * @author user
 */
public class KoTorrentInt {

    public byte[] bytes = new byte[4];
    
    public KoTorrentInt(int value) {
        if (value <= Integer.MAX_VALUE) {
            bytes[3] = (byte) (value % 256);
            bytes[2] = (byte) ((value >> 8) % (256));
            bytes[1] = (byte) ((value >> 16) % (256));
            bytes[0] = (byte) ((value >> 24) % (256));
        } else {
            System.err.println("input salah");
        }
    }

    public KoTorrentInt(byte[] bytes) {
        this.bytes = bytes;
    }

    public static int unsignedByteToInt(byte b) {
        return (int) b & 0xFF;
    }

    public byte[] getBytes() {
        return bytes;
    }

    public byte getByte(int i) {
        return bytes[i];
    }

    public int getInt() {
        int x;
        x = unsignedByteToInt(bytes[3]);
        x += unsignedByteToInt(bytes[2]) << 8;
        x += unsignedByteToInt(bytes[1]) << 16;
        x += unsignedByteToInt(bytes[0]) << 24;
        return x;
    }

    public static byte[] appendBytes(byte[] a, byte[] b) {
        byte[] res = new byte[a.length+b.length];
        int i;
        for (i=0; i<a.length; ++i) {
            res[i] = a[i];
        }
        for (i=a.length; i<res.length; ++i) {
            res[i] = b[i-a.length];
        }
        return res;
    }

    public static byte[] appendBytesByte(byte[] a, byte b) {
        byte[] res = new byte[a.length+1];
        int i;
        for (i=0; i<a.length; ++i) {
            res[i] = a[i];
        }
        res[res.length-1] = b;
        return res;
    }

    public static byte[] appendByteBytes(byte a, byte[] b) {
        byte[] res = new byte[b.length+1];
        int i;
        res[0] = a;
        for (i=1; i<b.length; i++) {
            res[i] = b[i-1];
        }
        res[i] = b[b.length-1];
        return res;
    }

    public static String displayBytes(byte[] bytes) {
        String s = "";
        for (int i = 0; i<bytes.length; i++) {
            s += (int) bytes[i];
        }
        return s;
    }

    public static void main(String[] args){
        byte[] b = new byte[4];
        b[0] = (byte)3;
        b[1] = (byte)4;
        b[2] = (byte)5;
        b[3] = (byte)6;
        KoTorrentInt k = new KoTorrentInt(b);
        k.bytes = KoTorrentInt.appendByteBytes((byte)1, b);
        System.out.println(k.displayBytes(k.bytes));

    }

    
}
